package cn.com.guage.guc.sync;

/**
 * 
 * @author yangdechao
 *
 */

class Share2{
    private int number=0;

    //+1
    public synchronized void inc() throws InterruptedException {
    	//替换为while后,即使被唤醒,仍然会再检查一遍限制条件,保证逻辑的正确性.
        while(number!=0){
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"::"+number);
        this.notifyAll();
    }

    //-1
    public synchronized void dec() throws InterruptedException {
    	while(number!=1){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"::"+number);
        this.notifyAll();
    }

}
public class ThreadDemo2 {

    public static void main(String[] args) {
        Share2 share2=new Share2();
        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share2.inc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share2.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share2.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();
        
        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    share2.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }

}
